//文件显示类
#pragma once

#include <ncurses.h>
#include <vector>
#include <string>
#include <fstream>
#include <unordered_set>

class FileDisplay
{
private:
    // Shell关键字集合
    const std::unordered_set<std::string> SHELL_KEYWORDS = {
        "if", "then", "else", "elif", "fi", "case", "esac", "for",
        "while", "until", "do", "done", "in", "function", "select"};

    // 定义语法高亮类型
    enum class HighlightType
    {
        NORMAL,
        KEYWORD,
        STRING,
        COMMENT,
        NUMBER,
        VARIABLE,
        SYMBOL
    };

    WINDOW *win;
    std::string file_name;
    std::vector<std::string> original_lines;
    std::vector<std::vector<HighlightType>> highlight_info;
    std::vector<std::pair<std::string, std::vector<HighlightType>>> wrapped_lines;
    int top_line;
    int win_height;
    int win_width;

public:
    //构建函数
    FileDisplay(WINDOW *window, const std::string &file)
        : file_name(file), top_line(0)
    {
        int h, w;
        getmaxyx(window, h, w);
        win = derwin(window, h - 2, w - 2, 1, 1);
        getmaxyx(win, win_height, win_width);
        initialize_colors();
        load_file(file_name);
        analyze_syntax();
        rewrap_lines();
    }

    //析构函数
    ~FileDisplay()
    {
        delwin(win);
    }

    //初始化颜色
    void initialize_colors();
    //读取文件
    bool load_file(const std::string &filename);
    //分析语法高亮
    void analyze_syntax();
    // 重新计算换行
    void rewrap_lines();
    //刷新显示
    void refresh_display();
    //处理输入
    bool handle_input(int ch);

    void run(){
        refresh_display();
    }
    //重新加载文件
    bool reload_file(){
        if(!load_file(file_name))
            return false;
        analyze_syntax();
        rewrap_lines();
        refresh_display();
        return true;
    }
    //改变文件
    bool change_file(const std::string &newFile)
    {
        wrefresh(win);
        werase(win);
        top_line = 0;
        file_name = newFile;
        return reload_file();
    }
};